﻿using MG.Library.Models;
using Microsoft.AspNetCore.Components;

namespace MG.Library.Pages;

public partial class Detail
{
    [Parameter]
    public string Id { get; set; }//bug

    private Mg _mg = new();

    private bool _isLoadingMg = true;

    private bool _isLoadingFavorite = true;

    private Favorite _favorite = new();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender)
        {
            return;
        }

        if (string.IsNullOrWhiteSpace(Id))
        {
            return;
        }

        if (!int.TryParse(Id, out var mgId))
        {
            return;
        }

        _isLoadingMg = true;
        StateHasChanged();

        _mg = await _mgStorage.GetMgAsync(mgId) ?? new Mg()
            ;
        _isLoadingMg = false;
        StateHasChanged();

        _favorite = await _favoriteStorage.GetFavoriteAsync(_mg.Id) ??
                    new Models.Favorite { MgId = _mg.Id };
        _isLoadingFavorite = false;
        StateHasChanged();
    }

    private async Task ValueChanged()
    {
        _isLoadingFavorite = true;
        StateHasChanged();

        await _favoriteStorage.SaveFavoriteAsync(_favorite);

        _isLoadingFavorite = false;
        StateHasChanged();
    }
}